<?php
include('sys_data_fun.php');
if(!$date){
	$date=date('Ymd');
}
$bkdir = DUODUODATA . '/' . $cfg_backup_dir.'_'.$date;

if (empty ($dopost)) {
	$dopost = '';
}

//跳转到一下页的JS
$gotojs = "function GotoNextPage(){
	document.gonext." . "submit();
}" . "\r\nset" . "Timeout('GotoNextPage()',500);";

$dojs = "<script language='javascript'>$gotojs</script>";

$phpstart="<?php exit(0);?>\r\n";

if ($dopost == 'bak') {
	if (empty ($tablearr)) {
		ShowMsg('你没选中任何表！', 'javascript:;');
		exit ();
	}
	
	if (!is_dir($bkdir)) {
		MkdirAll($bkdir);
	}

	//初始化使用到的变量
	$tables = explode(',', $tablearr);
	if (!isset ($isstruct)) {
		$isstruct = 0;
	}
	if (!isset ($startpos)) {
		$startpos = 0;
	}
	if (!isset ($iszip)) {
		$iszip = 0;
	}
	if (empty ($nowtable)) {
		$nowtable = '';
	}
	if (empty ($fsize)) {
		$fsize = 2048;
	}
	$fsizeb = $fsize * 1024;

	if ($nowtable == '') {
		$tmsg = '';
		$dh = dir($bkdir);
		while ($filename = $dh->read()) {
			if (!ereg("php$", $filename)) {
				continue;
			}
			$filename = $bkdir . "/$filename";
			if (!is_dir($filename)) {
				unlink($filename);
			}
		}
		$dh->close();
		$tmsg .= "清除备份目录旧数据完成...<br />";

		if ($isstruct == 1) {
			$bkfile = $bkdir . "/tables_struct_" . substr(md5(time() . mt_rand(1000, 5000) . $cfg_cookie_encode), 0, 16) . ".php";
			$mysql_version = GetVersion();
			$fp = fopen($bkfile, "w");
			fwrite($fp, $phpstart);
			foreach ($tables as $t) {
				fwrite($fp, "DROP TABLE IF EXISTS `$t`;\r\n\r\n");
				$sql_show_table = "SHOW CREATE TABLE `" . $dbname . "`.`" . $t."`";
				$query_show_table = mysql_query($sql_show_table);
				$row = mysql_fetch_array($query_show_table, MYSQL_BOTH);
				//去除AUTO_INCREMENT
				$row[1] = eregi_replace("AUTO_INCREMENT=([0-9]{1,})[ \r\n\t]{1,}", "", $row[1]);

				//4.1以下版本备份为低版本
				if ($datatype == 4.0 && $mysql_version > 4.0) {
					$eng1 = "ENGINE=MyISAM[ \r\n\t]{1,}DEFAULT[ \r\n\t]{1,}CHARSET=" . $cfg_db_language;
					$tableStruct = eregi_replace($eng1, "TYPE=MyISAM", $row[1]);
				}

				//4.1以下版本备份为高版本
				else
					if ($datatype == 4.1 && $mysql_version < 4.1) {
						$eng1 = "ENGINE=MyISAM DEFAULT CHARSET={$cfg_db_language}";
						$tableStruct = eregi_replace("TYPE=MyISAM", $eng1, $row[1]);
					}

				//普通备份
				else {
					$tableStruct = $row[1];
				}
				fwrite($fp, '' . $tableStruct . ";\r\n\r\n");
			}
			fclose($fp);
			$tmsg .= "备份数据表结构信息完成...<br />";
		}

		$tmsg .= "<font color='red'>正在进行数据备份的初始化工作，请稍后...</font>";
		$doneForm = "<form name='gonext' method='post' action='sys_data_done.php'>
		           <input type='hidden' name='isstruct' value='$isstruct' />
		           <input type='hidden' name='dopost' value='bak' />
		           <input type='hidden' name='fsize' value='$fsize' />
		           <input type='hidden' name='tablearr' value='$tablearr' />
				   <input type='hidden' name='date' value='$date' />
		           <input type='hidden' name='nowtable' value='{$tables[0]}' />
		           <input type='hidden' name='startpos' value='0' />
		           <input type='hidden' name='iszip' value='$iszip' />\r\n</form>\r\n{$dojs}\r\n";
		PutInfo($tmsg, $doneForm);
		exit ();
	}
	//执行分页备份
	else {
		$j = 0;
		$fs = $bakStr = '';
		$values_str='';

		//分析表里的字段信息
		$sql_fields = mysql_list_fields($dbname,$nowtable);
		$columns = mysql_num_fields($sql_fields);
		
		//读取表的内容
		$sq_table ="Select * From `$nowtable` ";
		$query_table = mysql_query($sq_table);

		for ($i = 0; $i < $columns; $i++) {
			$field_type=mysql_field_type($query_table, $i);
			$fs[$j]['name'] = trim(mysql_field_name($sql_fields, $i));
			$fs[$j]['type'] = $field_type;
			if($values_str==''){$values_str.='`'.$fs[$j]['name'].'`';}
			else{$values_str.=','.'`'.$fs[$j]['name'].'`';}
			$j++;
		}
		$fsd = $j -1;
		$intable = "INSERT INTO `$nowtable` (".$values_str.") VALUES(";
		
		$m = 0;
		$bakfilename = "$bkdir/{$nowtable}_{$startpos}_" . substr(md5(time() . mt_rand(1000, 5000) . $cfg_cookie_encode), 0, 16) . ".php";
		while ($row2 = mysql_fetch_array($query_table)) {
			if ($m < $startpos) {
				$m++;
				continue;
			}

			//检测数据是否达到规定大小
			if (strlen($bakStr) > $fsizeb) {
				$fp = fopen($bakfilename, "w");
				fwrite($fp, $phpstart.$bakStr);
				fclose($fp);
				$tmsg = "<font color='red'>完成到{$m}条记录的备份，继续备份{$nowtable}...</font>";
				$doneForm = "<form name='gonext' method='post' action='sys_data_done.php'>
				                <input type='hidden' name='isstruct' value='$isstruct' />
				                <input type='hidden' name='dopost' value='bak' />
				                <input type='hidden' name='fsize' value='$fsize' />
				                <input type='hidden' name='tablearr' value='$tablearr' />
				                <input type='hidden' name='nowtable' value='$nowtable' />
								<input type='hidden' name='date' value='$date' />
				                <input type='hidden' name='startpos' value='$m' />
				                <input type='hidden' name='iszip' value='$iszip' />\r\n</form>\r\n{$dojs}\r\n";
				PutInfo($tmsg, $doneForm);
				exit ();
			}

			//正常情况
			$line = $intable;
			for ($j = 0; $j <= $fsd; $j++) {
				$field_value=$row2[$fs[$j]['name']];
				if($field_value==''){
					if($fs[$j]['type']=='string'){
					    $field_value="''";
					}
					else{
					    $field_value='NULL';
					}
					if ($j < $fsd) {
					    $line .= $field_value . ",";
				    } else {
					    $line .= $field_value . ");\r\n";
				    }
				}
				else{
				    $field_value=RpLine(addslashes($field_value));
					if ($j < $fsd) {
					    $line .= "'" . $field_value . "',";
				    } else {
					    $line .= "'" . $field_value . "');\r\n";
				    }
				}
			}
			$m++;
			$bakStr .= $line;
		}

		//如果数据比卷设置值小
		if ($bakStr != '') {
			$fp = fopen($bakfilename, "w");
			fwrite($fp, $phpstart.$bakStr);
			fclose($fp);
		}
		for ($i = 0; $i < count($tables); $i++) {
			if ($tables[$i] == $nowtable) {
				if (isset ($tables[$i +1])) {
					$nowtable = $tables[$i +1];
					$startpos = 0;
					break;
				} else {
					PutInfo("完成所有数据备份！", "");
					exit ();
				}
			}
		}
		$tmsg = "<font color='red'>完成到{$m}条记录的备份，继续备份{$nowtable}...</font>";
		$doneForm = "<form name='gonext' method='post' action='sys_data_done.php?dopost=bak'>
		          <input type='hidden' name='isstruct' value='$isstruct' />
		          <input type='hidden' name='fsize' value='$fsize' />
		          <input type='hidden' name='tablearr' value='$tablearr' />
		          <input type='hidden' name='nowtable' value='$nowtable' />
				  <input type='hidden' name='date' value='$date' />
		          <input type='hidden' name='startpos' value='$startpos'>\r\n</form>\r\n{$dojs}\r\n";
		PutInfo($tmsg, $doneForm);
		exit ();
	}
	//分页备份代码结束
}

/*-------------------------
还原数据
function __re_data();
-------------------------*/
else if($dopost=='redat')
{
	if($bakfiles=='')
	{
		ShowMsg('没指定任何要还原的文件!','javascript:;');
		exit();
	}
	$bakfilesTmp = $bakfiles;
	$bakfiles = explode(',',$bakfiles);
	if(empty($structfile))
	{
		$structfile = "";
	}
	if(empty($delfile))
	{
		$delfile = 0;
	}
	if(empty($startgo))
	{
		$startgo = 0;
	}
	if($startgo==0 && $structfile!='')
	{
		$tbdata = '';
		$fp = fopen("$bkdir/$structfile",'r');
		while(!feof($fp))
		{
			$tbdata .= str_replace($phpstart,'',fgets($fp,1024));
		}
		fclose($fp);
		$querys = explode(';',$tbdata);
        
		if($keepdb!=1){
		    foreach($querys as $q){
			    mysql_query(trim($q).';');
			}
		}
		else{
		    $sql = "Show Tables";
            $query = mysql_query($sql);
            while ($row = mysql_fetch_array($query)) {
                $sql="TRUNCATE TABLE `".$row[0]."`"; 
				mysql_query($sql);
	        }
		}
		if($delfile==1)
		{
			@unlink("$bkdir/$structfile");
		}
		$tmsg = "<font color='red'>完成数据表信息还原，准备还原数据...</font>";
		$doneForm = "<form name='gonext' method='post' action='sys_data_done.php?dopost=redat'>
        <input type='hidden' name='startgo' value='1' />
        <input type='hidden' name='delfile' value='$delfile' />
        <input type='hidden' name='bakfiles' value='$bakfilesTmp' />
		<input type='hidden' name='date' value='$date' />
		</form>\r\n{$dojs}\r\n";
		PutInfo($tmsg,$doneForm);
		exit();
	}
	else
	{
		$nowfile = $bakfiles[0];
		$bakfilesTmp = ereg_replace($nowfile."[,]{0,1}","",$bakfilesTmp);
		$oknum=0;
		if( filesize("$bkdir/$nowfile") > 0 )
		{
			$fp = fopen("$bkdir/$nowfile",'r');
			while(!feof($fp))
			{
				$line = trim(fgets($fp,512*1024));
				if($line=="")
				{
					continue;
				}
				$rs = mysql_query($line);
				if($rs)
				{
					$oknum++;
				}
			}
			fclose($fp);
		}
		if($delfile==1)
		{
			@unlink("$bkdir/$nowfile");
		}
		if($bakfilesTmp=="")
		{
			ShowMsg('成功还原所有的文件的数据!','javascript:;');
			if($delfile==1){
		        rmdir($bkdir);//删除目录，可能会不好用，提示权限不足，暂时没有找到解决办法
			}
			exit();
		}
		$tmsg = "成功还原{$nowfile}的{$oknum}条记录<br/><br/>正在准备还原其它数据...";
		$doneForm = "<form name='gonext' method='post' action='sys_data_done.php?dopost=redat'>
		<input type='hidden' name='startgo' value='1' />
		<input type='hidden' name='delfile' value='$delfile' />
		<input type='hidden' name='bakfiles' value='$bakfilesTmp' />
		<input type='hidden' name='date' value='$date' />
		</form>\r\n{$dojs}\r\n";
		PutInfo($tmsg,$doneForm);
		exit();
	}
}
mysql_close();
?>
